import { login as loginApi } from '@/api/login'
import router from '@/router'
import { setTokenTime } from '@/utils/auth'

export default {
  namespaced: true,
  state: () => ({
    token: localStorage.getItem('token') || '',
    siderType: true
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    setUserId(state, userId) {
      state.userId = userId
      localStorage.setItem('userId', userId)
    },
    changeSiderType(state) {
      state.siderType = !state.siderType
    }
  },
  actions: {
    login({ commit }, userInfo) {
        const { account, password } = userInfo
        return new Promise((resolve, reject) => {
          loginApi({ account: account.trim(), password: password.trim() })
          .then(res => {
            if (res.data) {
              commit('setToken', res.data.token) // 从 data 中获取 token
              commit('setUserId', res.data.user_id)
              setTokenTime()
              router.push('/home')
              resolve(res)
            } else {
              reject(new Error(res.message || '登录失败'))
            }
          })
          .catch(err => {
            console.error('Login Error:', err)
            reject(err)
          })
      })
    },
    logout({ commit }) {
        commit('setToken', '')
        commit('setUserId', '')
        localStorage.clear()
        router.push('/login')
    }
  }
}
